package cn.edu.java.thread.锁;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class WriteLockDemo {

    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private static ArrayList<String> arrayList = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        Runnable writeData = new Runnable() {
            @Override
            public void run() {
                writeLock.lock();
                try {
                    // 模拟写操作
                    System.out.println("Thread " + Thread.currentThread().getId() + " is writing data.");
                    arrayList.add(Thread.currentThread().getName());
                    Thread.sleep(1000); // 模拟耗时操作
                    System.out.println("Thread " + Thread.currentThread().getId() + " writes data: " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    writeLock.unlock();
                }
            }
        };


        new Thread(writeData).start();
        new Thread(writeData).start();

        Thread.sleep(2000); // 等待
        System.out.println(arrayList);

    }


}
